import { AppDataSource } from "@/config/database";
import { User } from "@/entities/system/user.entity";
import { generateToken } from "@/utils/token.util";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { TokenManager } from "@/config/redis";
import { Context } from "koa";
import * as CryptoJS from 'crypto-js';

export const login = async (ctx: Context) => {
    const { username, password } = ctx.request.body as { username: string, password: string };

    validateParams(username, password); // 校验参数
    const user = await findUserByUsername(username); // 用用户名查询用户
    validatePassword(user, password); // 校验用户的密码是否正确

    // 生成 token
    const token = generateToken(user);
    
    // 将token存储到Redis，覆盖之前的token（实现单一登录）
    await TokenManager.setUserToken(user.id, token);

    ctx.status = 200;
    ctx.body = { token };
}

/** 校验参数 */
const validateParams = (username: string, password: string) => {
    if (!username || !password) {
        throw new Error('用户名和密码不能为空');
    }
}

/** 用用户名查询用户 */
const findUserByUsername = async (username: string) => {
    const userRepository = AppDataSource.getRepository(User);
    const user = await userRepository.findOne({
        where: { username },
    });

    if (!user) {
        throw new ErrorHandler('用户不存在', 404);
    }

    return user;
}

/** 校验用户的密码是否正确 */
const validatePassword = (user: User, password: string) => {
    const hashedPassword = CryptoJS.MD5(password).toString();
    if (user.password !== hashedPassword) {
        throw new Error('密码错误');
    }
}